package yh.thread.threadpoolcreate;


import org.junit.Test;

import java.util.concurrent.*;

/**
 * 最原始的方式创建线程
 *
 * @author: zyh
 * @date: 2024/10/18 16:08
 **/
public class ThreadPoolCreateTest {


    /**
     * java 标准类库中的类，提供线程池的基本功能
     */
    @Test
    public void threadPoolExecutor() throws ExecutionException, InterruptedException {

        //提供4种构造方法,下面这个是全参构造
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                1,
                5,
                60,
                TimeUnit.SECONDS,
               new LinkedBlockingQueue(100),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());



        //使用 runnable 执行 new Runnable() 可省略
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                //模拟执行业务
                System.out.println("当前线程：" + System.currentTimeMillis() + Thread.currentThread().getName() + "执行任务中.....");

            }
        });


        //使用 new Callable<Boolean>执行
        Future<Boolean> futureCall = threadPoolExecutor.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return null;
            }
        });

        //使用 new Runnable() 执行
        Future<?> futureRunnable = threadPoolExecutor.submit(new Runnable() {
            @Override
            public void run() {

            }
        });


        // Callable 简化写法,使用 submit 执行线程池
        Future<Boolean> futureResult = threadPoolExecutor.submit(() -> {
            System.out.println("当前线程：" + System.currentTimeMillis() + Thread.currentThread().getName() + "执行任务中.....");
            return true;

        });
        try {
            //获取线程池返回结果
            Boolean b = futureResult.get();
            System.out.println(b);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

    }



    /**
     * spring 框架中创建线程池的方式
     */
    public void threadPoolTaskExecutor(){

    }





}
